package com.zhenmyan.secdeal.controller;

import com.zhenmyan.secdeal.pojo.User;
import com.zhenmyan.secdeal.service.GoodsService;
import com.zhenmyan.secdeal.vo.DetailVo;
import com.zhenmyan.secdeal.vo.GoodsVo;
import com.zhenmyan.secdeal.vo.Response;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * description:
 *
 * @author 颜真明
 * @date 2023/5/9  16:03
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Resource
    private GoodsService goodsService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 跳转商品列表页
     *
     * @param model
     * @return
     */
    // @RequestMapping("/toList") 这里是做页面跳转
    // 优化手段是直接返回整个页面，将静态资源缓存在redis
    @RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model, User user, HttpServletRequest request, HttpServletResponse response) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String goodsListHtml = (String)valueOperations.get("goodsList");
        if (!StringUtils.isEmpty(goodsListHtml)) {
            return goodsListHtml;
        }
        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsService.getGoodsVo());

        // 如果为空，需要手动渲染，然后存储redis
        WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        // 整合模版和动态资源
        goodsListHtml = thymeleafViewResolver.getTemplateEngine().process("goodsList", webContext);
        if (!org.thymeleaf.util.StringUtils.isEmpty(goodsListHtml)) {
            valueOperations.set("goodsList", goodsListHtml, 60, TimeUnit.SECONDS);
        }
        return goodsListHtml;
    }

    /**
     * 采用模版引擎的方法获取详情页
     * 缓存html页面
     *
     * @param model
     * @param user
     * @param goodsId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/toDetailV1/{goodsId}", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetailV1(Model model, User user, @PathVariable Long goodsId, HttpServletRequest request, HttpServletResponse response) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String goodsDetail = (String)valueOperations.get("goodsDetail" + goodsId);
        if (!StringUtils.isEmpty(goodsDetail)) {
            return goodsDetail;
        }
        GoodsVo goodsVo = goodsService.getGoodsVoById(goodsId);
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        //秒杀状态
        int secDealStatus = 0;
        //秒杀倒计时
        int remainSeconds = 0;

        if (nowDate.before(startDate)) {
            //秒杀还未开始0
            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);
        } else if (nowDate.after(endDate)) {
            //秒杀已经结束
            secDealStatus = 2;
            remainSeconds = -1;
        } else {
            //秒杀进行中
            secDealStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("user", user);
        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("secDealStatus", secDealStatus);
        model.addAttribute("goods", goodsVo);
        WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        goodsDetail = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", webContext);
        if (!org.thymeleaf.util.StringUtils.isEmpty(goodsDetail)) {
            valueOperations.set("goodsList" + goodsId, goodsDetail, 60, TimeUnit.SECONDS);
        }
        return goodsDetail;
    }


    /**
     * 采用动静分离
     *
     * @param model
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping("/toDetail/{goodsId}")
    @ResponseBody
    public Response toDetail(Model model, User user, @PathVariable Long goodsId) {
        GoodsVo goodsVo = goodsService.getGoodsVoById(goodsId);
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        //秒杀状态
        int secDealStatus = 0;
        //秒杀倒计时
        int remainSeconds = 0;

        if (nowDate.before(startDate)) {
            //秒杀还未开始0
            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);
        } else if (nowDate.after(endDate)) {
            //秒杀已经结束
            secDealStatus = 2;
            remainSeconds = -1;
        } else {
            //秒杀进行中
            secDealStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("user", user);
        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("secDealStatus", secDealStatus);
        model.addAttribute("goods", goodsVo);
        DetailVo detailVo = new DetailVo();
        detailVo.setUser(user);
        detailVo.setGoodsVo(goodsVo);
        detailVo.setRemainSeconds(remainSeconds);
        detailVo.setSecDealStatus(secDealStatus);
        return Response.success(detailVo);
    }

}
